/*
* 操作文件数据
*   只处理数据，不关心业务
* */
let fs = require('fs')
let dbPath = './db.json'

//查询数据
exports.find = function (callback) {
    fs.readFile(dbPath, 'utf-8', function (err, data) {
        if (err) {
            return callback(err)
        }
        callback(null, JSON.parse(data).students)
    })
}

exports.findById = function (id, callback) {
    fs.readFile(dbPath, 'utf-8', function (err, data) {
        if (err) {
            return callback(err)
        }
        let students = JSON.parse(data).students

        let ret = students.find(function (item) {
            return item.id === parseInt(id)
        })

        callback(null, ret)

    })
}


//保存数据
exports.save = function (student, callback) {
    //读取文件数据
    fs.readFile(dbPath, 'utf-8', function (err, data) {
        if (err) {
            return callback(err)
        }
        let students = JSON.parse(data).students
        student.id = students[students.length - 1].id + 1
        students.push(student)

        //把对象数据转成字符串
        let fileDate = JSON.stringify({
            students: students
        })
        //将数据保存至文件
        fs.writeFile(dbPath, fileDate, function (err) {
            if (err) {
                return callback(err)
            }
            callback(null)
        })

    })
}


// 更新学生
exports.undataById = function (student, callback) {
    //读取文件数据
    fs.readFile(dbPath, 'utf-8', function (err, data) {
        if (err) {
            return callback(err)
        }
        let students = JSON.parse(data).students
        student.id = parseInt(student.id)

        //修改数据(根据id查找)
        // ecmaScript6数组方法----find
        let stu = students.find(function (item) {
            return item.id === student.id
        })

        for (let key in student) {
            stu[key] = student[key]
        }
        //把对象数据转成字符串
        let fileDate = JSON.stringify({
            students: students
        })
        //将数据保存至文件
        fs.writeFile(dbPath, fileDate, function (err) {
            if (err) {
                return callback(err)
            }
            callback(null)
        })
    })


}
//删除页面
exports.deleteById = function (id, callback) {
    fs.readFile(dbPath, 'utf-8', function (err, data) {
        if (err) {
            return callback(err)
        }
        let students = JSON.parse(data).students

        let deleteid = students.findIndex(function (item) {
            return item.id === parseInt(id)
        })

        students.splice(deleteid, 1)

        //把对象数据转成字符串
        let fileDate = JSON.stringify({
            students: students
        })
        //将数据保存至文件
        fs.writeFile(dbPath, fileDate, function (err) {
            if (err) {
                return callback(err)
            }
            callback(null)
        })

    })

}
